<!DOCTYPE html>
<html>
    <head>
    <title>SDK</title>
    <meta charset="utf-8">
    <meta name="format-detection" content="telephone=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <style>
    #scratch {position: absolute;top: 0;right: 0;bottom: 0;left: 0;}
    </style>
    <script src="./static/neurons_logic_engine.js"></script>
    </head>
    <body>
        <div id="scratch"></div>
    <script type="text/javascript" src="lib.min.js"></script><script type="text/javascript" src="mscratch.js"></script></body>
    <script type="text/javascript" src="./static/socket.io.js"></script>
    <!-- 初始化逻辑 -->

    <script>
        // 实例化
        var mscratch = new Mscratch({
            'lang': 'zh'
        });


        //注入
        mscratch.inject('scratch');

        mscratch.onRendered(() => {
            // 开启代码编辑
            mscratch.code.setCodeEditable(true);
            mscratch.code.setRunBtnVisible(true);
             // 假设外部已连接，并使用下面方法通告了连接状态
            mscratch.connection.onConnect((device) => {
                mscratch.connection.setState(device, true);
            });
            // 假设外部已连接，并使用下面方法通告了连接状态
            mscratch.connection.onDisconnect((device) => {
                mscratch.connection.setState(device, false);
            });

            // 监听上传进度
            mscratch.code.onProgress((err, data) => {
                console.log(err, data);
            });

            openSocket();

            const workerDescription = {
                id: 'workerExtension',
                name: {
                    en: 'Worker Extension',
                    zh: 'Worker扩展示例'
                },
                description: {
                    en: 'Worker Extension',
                    zh: 'Worker扩展示例'
                },
                basic: false,
                data: './static/extensions/demo/demo2.js',
                devices: null,
                autoRegistered: false
            };
            mscratch.extensions.appendExtensionToLibrary(workerDescription);
        });

        function openSocket () {
            // 由外部确定的传输通道
            var socket = io.connect('http://localhost:8800');

            //设置通道
            socket.on('sensor2web', function (data) {
                // console.log('local received ', data);
                mscratch.transporter.doReceived(JSON.parse(data));
            });
            let sender = function(buf) {
                if(buf instanceof Uint8Array) { // 兼容神经元
                    // console.log('buf', buf);
                    buf = Array.from(buf);
                }
                socket.emit('web2sensor', { buf: JSON.stringify(buf), sensor: 'None' });
            }
            mscratch.transporter.setSender(sender);
        }

    </script>
</html>
